$(function () {
  // 获取文章类别发起Ajax请求
  function initArtCateList() {
    $.ajax({
      method: "GET",
      url: "/my/article/cates",
      success: function (res) {
        const html = template("tpl-table", res);
        // 渲染数据
        $("tbody").html(html);
      },
    });
  }
  initArtCateList();

  const layer = layui.layer;
  const form = layui.form;
  //   给添加类别绑定点击事件
  var indexAdd = null;
  $("#btnAddCate").on("click", function () {
    indexAdd = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "添加文章分类",
      //   渲染弹出层
      content: $("#dialog-add").html(),
    });
  });

  //   给form-add添加submit事件
  $("body").on("submit", "#form-add", function (e) {
    e.preventDefault();
    // 发起Ajax请求
    $.ajax({
      method: "POST",
      url: "/my/article/addcates",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("添加失败");
        }
        initArtCateList();
        layer.msg("添加成功");
        // 根据索引关闭弹出层
        layer.close(indexAdd);
      },
    });
  });

  var indexEdit = null;
  $("tbody").on("click", ".btn-edit", function () {
    indexEdit = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "修改文章分类",
      //   渲染弹出层
      content: $("#dialog-edit").html(),
    });
    const id = $(this).data("id");
    $.ajax({
      method: "GET",
      url: "/my/article/cates/" + id,
      success: function (res) {
        console.log(res);
        form.val("form-edit", res.data);
      },
    });
  });

  $("body").on("submit", "#form-edit", function (e) {
    e.preventDefault();
    $.ajax({
      method: "POST",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("修改信息失败!");
        }
        layer.msg("修改成功");
        initArtCateList();
        layer.close(indexEdit);
      },
    });
  });

  $("tbody").on("click", ".btn-delete", function () {
    const id = $(this).data("id");
    // 提示用户是否要删除
    layer.confirm("确认删除?", { icon: 3, title: "提示" }, function (index) {
      $.ajax({
        method: "GET",
        url: "/my/article/deletecate/" + id,
        success: function (res) {
          if (res.status !== 0) {
            return layer.msg("删除分类失败！");
          }
          layer.msg("删除分类成功！");
          layer.close(index);
          initArtCateList();
        },
      });
    });
  });
});
